#pragma once
// control, 控制器，是我们的核心业务逻辑
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <cassert>
#include <mutex>
#include <cassert>
#include <algorithm>
#include <jsoncpp/json/json.h>

#include "../Comm/Log.hpp"
#include "../Comm/Util.hpp"
#include "../Comm/httplib.h"
//#include "Oj_model.hpp"
#include "Oj_model2.hpp"
#include "Oj_view.hpp"

namespace ns_control
{
    using namespace ns_Log;
    using namespace ns_Util;
    using namespace ns_model;
    using namespace ns_view;
    using namespace httplib;

    // 提供服务的主机
    class Machine
    {
    public:
        std::string ip;  // 编译服务ip
        int port;        // 编译服务端口号
        uint64_t load;   // 编译服务的负载
        std::mutex *mtx; // 这个必须使用指针，不然后续拷贝不了
    public:
        Machine()
            : ip(" "),
              port(0),
              load(0),
              mtx(nullptr)
        {
        }
        ~Machine()
        {
        }

    public:
        // 增加主机负载
        void Incload()
        {
            LOG(INFO) << "增加负载:" << port << "\n";
            mtx->lock();
            ++load;
            mtx->unlock();
        }
        // 减少主机负载
        void Decload()
        {
            LOG(INFO) << "减少负载:" << port << "\n";
            mtx->lock();
            --load;
            mtx->unlock();
        }
        // 将主机负载置零
        void Resetload()
        {
            mtx->lock();
            load = 0;
            mtx->unlock();
        }
        // 返回主机负载情况
        uint64_t Load()
        {
            uint64_t _load;
            mtx->lock();
            _load = load;
            mtx->unlock();

            return _load;
        }
        std::string Ip()
        {
            std::string _ip;
            mtx->lock();
            _ip = ip;
            mtx->unlock();

            return _ip;
        }
        int Port()
        {
            int _port;
            mtx->lock();
            _port = port;
            mtx->unlock();

            return _port;
        }
    };

    const std::string service_machine = "./conf/service_machine.conf";

    // 负载均衡模块
    class LoadBlance
    {
    private:
        // 该模块展示可以提供编译服务的主机
        // 每个主机都有自己的ip信息等
        std::vector<Machine> machine;
        // 在线的主机数
        std::vector<int> online;
        // 离线的主机数
        std::vector<int> offline;
        // 锁提供安全
        std::mutex mtx;

    public:
        LoadBlance()
        {
            assert(LoadConf(service_machine));
            LOG(INFO) << "加载" << service_machine << "成功" << "\n";
        }
        ~LoadBlance() {}

    public:
        // 加载服务机器
        bool LoadConf(const std::string &machine_conf)
        {
            std::ifstream in(machine_conf);
            if (!in.is_open())
            {
                LOG(FATAL) << "加载" << machine_conf << "失败" << "\n";
                return false;
            }
            // 分割service_machine.conf中字符串
            std::string line;
            while (getline(in, line))
            {
                std::vector<std::string> tokens;
                std::string sep = ":";
                StringUtil::SplitString(line, &tokens, sep);
                if (tokens.size() != 2)
                {
                    LOG(WARNING) << "切分" << line << "失败";
                    return false;
                }
                Machine m;
                m.ip = tokens[0];
                m.port = atoi(tokens[1].c_str());
                m.load = 0;
                m.mtx = new std::mutex();

                online.push_back(machine.size());
                machine.push_back(m);
                LOG(FATAL) << m.ip << ":" << m.port << " 添加成功\n";
            }
            in.close();

            return true;
        }
        // 选取负载最小机器
        bool SmartChoice(int *id, Machine **m)
        {
            // 查看当前在线主机数
            mtx.lock();
            int online_num = online.size();
            if (online_num == 0)
            {
                LOG(FATAL) << "当前没有编译服务机器在线" << "\n";
                return false;
            }
            // 通过遍历的方式查询负载最小的主机   
            *id = online[0];
            // 因为这里需要取machine地址所以参数需要改为**
            *m = &machine[online[0]];
            uint64_t min_load = machine[online[0]].Load();
            for (int i = 1; i < online.size(); i++)
            {
                LOG(INFO) << machine[online[i]].ip << ":" << machine[online[i]].port << " 负载:" << machine[online[i]].load << "\n";
                uint64_t curr_load = machine[online[i]].Load();
                if (min_load > curr_load)
                {
                    min_load = curr_load;
                    *id = online[i];
                    *m = &machine[online[i]];
                }
            }
            mtx.unlock();
            return true;
        }

        void OfflineMachine(int which)
        {
            mtx.lock();
            for (auto iter = online.begin(); iter != online.end(); iter++)
            {
                // 找到离线的主机
                if (*iter == which)
                {
                    LOG(FATAL) << machine[which].ip << ":" << machine[which].port << " 主机下线\n";
                    machine[which].Resetload();
                    // 在在线列表中删除,在离线列表中加入
                    online.erase(iter);
                    offline.push_back(which);
                    break;
                }
            }
            mtx.unlock();
        }
        void OnlineMachine()
        {
            mtx.lock();
            online.insert(online.end(), offline.begin(), offline.end());
            offline.erase(offline.begin(), offline.end());
            mtx.unlock();

            LOG(INFO) << "所有主机已上线" << "\n";
        }
        // 调试作用
        void ShowMachine()
        {
            mtx.lock();
            std::cout << "当前在线主机列表: ";
            for (auto &id : online)
            {
                std::cout << id << " ";
            }
            std::cout << std::endl;

            std::cout << "当前离线主机列表: ";
            for (auto &id : offline)
            {
                std::cout << id << " ";
            }
            std::cout << std::endl;
            mtx.unlock();
        }
    };
    // 核心业务逻辑控制器
    class Control
    {
    private:
        Model model_;            // 提供后台数据
        View view_;              // 提供html渲染网页
        LoadBlance load_blance_; // 核心负载均衡器
    public:
        Control()
        {
        }
        ~Control()
        {
        }

    public:
        //上线主机
        void RecoveryMachine()
        {
            load_blance_.OnlineMachine();
        }
        // 根据题目数据构建网业
        bool AllQuestions(std::string *html)
        {
            bool ret = true;
            std::vector<Question> all;
            // 获取题目数据
            if (model_.GetAllQuestions(&all))
            {
                //排序题目编号
                sort(all.begin(), all.end(), [](const struct Question &q1, const struct Question &q2)
                {
                    return atoi(q1.number.c_str()) < atoi(q2.number.c_str());
                });
                // 获取所有的题目数据成功，将题目数据构成网页
                view_.AllExpandHtml(all, html);
            }
            else
            {
                // 获取全部题目数据失败
                *html = "获取全部题目数据失败";
                ret = false;
            }
            return ret;
        }
        bool OneQuestion(std::string &number, std::string *html)
        {
            bool ret = true;
            struct Question q;
            if (model_.GetOneQuestion(number, &q))
            {
                // 获取单个题目，将题目数据构成网页
                view_.OneExpandHtml(q, html);
            }
            else
            {
                *html = "获取指定题目:" + number + "失败";
                ret = false;
            }
            return ret;
        }
        // 判题模块
        void judge(const std::string &number, const std::string in_json, std::string *out_json)
        {
            // 1.获取题目
            Question q;
            model_.GetOneQuestion(number, &q);

            // 2.反序列化，得到用户的id和提交的源代码
            Json::Reader reader;
            Json::Value in_value;
            reader.parse(in_json, in_value);
            std::string code = in_value["code"].asString();

            // 3.拼接用户代码和测试用例代码，形成新的代码
            Json::Value compiler_value;
            compiler_value["input"] = in_value["input"].asString();
            compiler_value["code"] = code + "\n" + q.tail; // 重点
            compiler_value["cpu_limit"] = q.cpu_limit;
            compiler_value["mem_limit"] = q.mem_limit;
            Json::FastWriter writer;
            std::string compiler_string = writer.write(compiler_value);
            
            // 4.选择负载最低的主机
            // 规则是:一直循环的查找主机,直到查找到能用的主机为止,否则就全部挂掉
            while (true)
            {
                int id = 0;
                Machine *m = nullptr;
                // 寻找负载最小的主机，没找到break继续寻找
                if (!load_blance_.SmartChoice(&id, &m))
                {
                    break;
                }

                // 5.发起http请求,得到结果
                Client cli(m->ip, m->port);
                m->Incload();
                LOG(INFO) << "选择主机成功，id：" << id << "详细信息：" << m->ip
                          << ":" << m->port << " 当前机器负载情况：" << m->Load() << "\n";
                
                load_blance_.ShowMachine();   
                std::cout << "主机id：" << id <<"主机的详细信息：" << m->Ip() << " " << m->Port() << std::endl;
                if (auto res = cli.Post("/compiler_run", compiler_string, "application/json;charset=utf-8"))
                {
                    // 6.将结果赋值给out_json
                    if (res->status == 200)
                    {
                        *out_json = res->body;
                        m->Decload();
                        LOG(INFO) << "请求编译运行服务成功！" << "\n";
                        break;
                    }
                    m->Decload();
                }
                else
                {
                    // 请求失败
                    LOG(ERROR) << " 当前请求的主机id: " << id << " 详情: " << m->ip
                               << ":" << m->port << " 可能已经离线" << "\n";
                    load_blance_.OfflineMachine(id);
                    // 调试作用
                    load_blance_.ShowMachine();
                }
            }
        }
    };
}